package cn.yhbk.web.modules.manager.Controller;

import cn.hutool.core.bean.BeanUtil;

import cn.yhbk.web.common.Util.MyUtil;
import cn.yhbk.web.common.api.CommonResult;
import cn.yhbk.web.modules.manager.Pojo.DTO.Apply.TbApplyDto;
import cn.yhbk.web.modules.manager.Pojo.DTO.Gpa.GpaDto;
import cn.yhbk.web.modules.manager.Pojo.DTO.ScholarShip.ScholarShipDto;
import cn.yhbk.web.modules.manager.Pojo.Entity.*;
import cn.yhbk.web.modules.manager.Pojo.VO.Apply.ApplyAdd;
import cn.yhbk.web.modules.manager.Pojo.VO.Apply.ApplyPag;
import cn.yhbk.web.modules.manager.Pojo.VO.Apply.ApplyResp;
import cn.yhbk.web.modules.manager.Pojo.VO.Apply.ApplyUpdate;
import cn.yhbk.web.modules.manager.Service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 奖学金申请表 前端控制器
 * </p>
 *
 * @author 有何不可
 * @since 2023-08-05
 */
@RestController
@Slf4j
@Api(tags = "奖学金申请接口")
@RequestMapping("/tbApply")
public class TbApplyController {

    @Autowired
    private ITbApplyService iTbApplyService;

    @Autowired
    private ITbStudentService iTbStudentService;

    @Autowired
    private ITbGpaRecordService iTbGpaRecordService;

    @Autowired
    private ITbScholarshipService iTbScholarshipService;

    @Autowired
    private ITbClassService classService;

    @Autowired
    private IOrderResultItemService orderResultItemService;


    @ApiOperation("根据ID获取申请表")
    @GetMapping("/getApply")
    public CommonResult<TbApplyDto> getApply(@RequestParam("id") Long id){
        log.info("查询申请表，id:" + id);
        TbApplyDto tbApply = iTbApplyService.getApplyById(id);
        return CommonResult.success("获取申请表成功", tbApply);
    }

//    @ApiOperation("学生申请奖学金")
//    @PostMapping("/student/saveApply")
//    public CommonResult<String> saveApply(@RequestBody ApplyAdd applyAdd){
//        Long adminStuId = MyUtil.getCurrentAdminId();
//        TbStudent student = iTbStudentService.getStudentByAdminId(adminStuId);
//
//        // 查询用户是否有资格申请
//        Boolean flag = iTbApplyService.apply(student.getId());
//        if (!flag){
//            return CommonResult.failed("暂无无资格申请");
//        }
//
//        // 查询用户是否已经申请过了
//        LocalDateTime now = LocalDateTime.now();
//        String year = String.valueOf(now.getYear());
//        TbApply apply = iTbApplyService.getOne(new QueryWrapper<TbApply>().eq("stu_id", student.getId()).eq("year", year)
//        .eq("scholarship_id", applyAdd.getScholarshipId()));
//        if (apply != null){
//            return CommonResult.failed("今年已经申请过了，请勿重复");
//        }
//
//        // 检查该奖学金是否在开始申请时间段
//        TbScholarship scholarship = iTbScholarshipService.getById(applyAdd.getScholarshipId());
//        if (now.isAfter(scholarship.getEndTime()) || now.isBefore(scholarship.getStartTime())){
//            return CommonResult.failed("未在申请规定时间段");
//        }
//
//        TbApply tbApply = BeanUtil.copyProperties(applyAdd, TbApply.class);
//        tbApply.setCreateTime(LocalDateTime.now());
//        tbApply.setUpdateTime(LocalDateTime.now());
//        tbApply.setStatus(1);
//        tbApply.setStuId(student.getId());
//        tbApply.setYear(year);
//        // 保存申请表
//        Boolean saveApply = iTbApplyService.save(tbApply);
//        if(!saveApply){
//            return CommonResult.failed("保存申请表出错");
//        }
//        return CommonResult.success("保存成功");
//    }

    @ApiOperation("学生申请奖学金")
    @PostMapping("/student/saveApply")
    public CommonResult<String> saveApply(@RequestBody ApplyAdd applyAdd){
        Long adminStuId = MyUtil.getCurrentAdminId();
        TbStudent student = iTbStudentService.getStudentByAdminId(adminStuId);
        TbClass tbClass = classService.getOne(new QueryWrapper<TbClass>().select("major_id, grade_id, description").eq("id", student.getClassId()));
        Boolean flag = iTbApplyService.apply(student, tbClass, applyAdd.getScholarshipId());
        if (flag) {
            return CommonResult.success("操作成功");
        }
        else{
            return CommonResult.failed("无资格申请该奖学金");
        }

    }

//    @ApiOperation("查询学生能够申请的奖学金【检验是否有资格申请】")
//    @GetMapping("/student/qualification")
//    public CommonResult<List<ScholarShipDto>> getStuQualification(){
//        Long adminStuId = MyUtil.getCurrentAdminId();
//        TbStudent student = iTbStudentService.getStudentByAdminId(adminStuId);
//
//        // 查询用户是否挂科
//        TbGpaRecord gpaRecord = iTbGpaRecordService.getOne(new QueryWrapper<TbGpaRecord>().eq("stu_id", student.getId()));
//        if(gpaRecord == null || !gpaRecord.getPass()){
//            return CommonResult.failed("挂科无法申请奖学金");
//        }
//
//        return CommonResult.success(iTbApplyService.getStuQualification(student.getId()));
//    }

    @ApiOperation("更新申请表")
    @PutMapping("/student/updateApply")
    public CommonResult<String> updateApply(@RequestBody ApplyUpdate applyUpdate){
        log.info("更新申请表," + applyUpdate);
        TbApply tbApply = iTbApplyService.getById(applyUpdate.getId());
        BeanUtils.copyProperties(applyUpdate, tbApply);
        tbApply.setUpdateTime(LocalDateTime.now());
        Boolean updateApply = iTbApplyService.updateById(tbApply);
        if(!updateApply){
            return CommonResult.failed("更新申请表出错");
        }
        return CommonResult.success("更新成功");
    }

    @ApiOperation("删除申请表")
    @DeleteMapping("/student/deleteApply/{applyId}")
    public CommonResult<String> deleteApply(@PathVariable("applyId") Long applyId){
        log.info("删除申请表,id:" + applyId);
        Boolean deleteApply = iTbApplyService.removeApply(applyId);
        if(!deleteApply){
            return CommonResult.failed("删除申请表出错");
        }
        return CommonResult.success("删除成功");
    }

    @ApiOperation("学工办分页获取奖学金申请")
    @GetMapping("/manager/getApplyInfoPag")
    public CommonResult<ApplyPag> getClassInfoPag(@RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                                  @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
                                                  @RequestParam(name = "typeId", required = false) Long typeId,
                                                  @RequestParam(name = "scholarshipId", required = false) Long scholarshipId,
                                                  @RequestParam(name = "year", required = false) String year,
                                                  @RequestParam(name = "jobNumber", required = false) Long jobNumber,
                                                  @RequestParam(name = "majorId", required = false) Long majorId,
                                                  @RequestParam(name = "status", required = false) Integer status){
        ApplyPag applyInfoPag = iTbApplyService.getApplyInfoPag(currentPage, pageSize, typeId, scholarshipId, year, jobNumber, majorId, status);
        return CommonResult.success(applyInfoPag);
    }

    @ApiOperation("学生分页获取自己的奖学金申请")
    @GetMapping("/student/getStuApplyInfoPag")
    public CommonResult<ApplyPag> getStuApplyInfoPag(@RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                                     @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
                                                     @RequestParam(name = "typeId", required = false) Long typeId,
                                                     @RequestParam(name = "scholarshipId", required = false) Long scholarshipId,
                                                     @RequestParam(name = "year", required = false) String year,
                                                     @RequestParam(name = "status", required = false) Integer status){
        ApplyPag applyInfoPag = iTbApplyService.getStuApplyInfoPag(currentPage, pageSize, typeId, scholarshipId, year, status);
        return CommonResult.success(applyInfoPag);
    }

    @ApiOperation("审核申请表，1同意，0不同意")
    @PutMapping("/manager/acceptApply/{applyId}/{status}")
    public CommonResult<String> acceptApply(@PathVariable("applyId") Long applyId,
                                            @PathVariable("status") Integer status){
        Boolean get = iTbApplyService.acceptApply(applyId, status);
        if(!get){
            return CommonResult.success("审核出错");
        }
        return CommonResult.success("审核成功");
    }

    @ApiOperation("导出申请Excle")
    @GetMapping("/getApplyExcel")
    public void getApplyExcel(@RequestParam(name = "name", required = false) String name,
                              @RequestParam(name = "typeId", required = false) Long typeId,
                              @RequestParam(name = "scholarshipId", required = false) Long scholarshipId,
                              @RequestParam(name = "year", required = false) String year,
                              @RequestParam(name = "jobNumber", required = false) Long jobNumber,
                              @RequestParam(name = "majorId", required = false) Long majorId,
                              @RequestParam(name = "status", required = false) Integer status){
        iTbApplyService.getApplyExcel(name, typeId, scholarshipId, year, jobNumber ,majorId, status);
    }

    @ApiOperation("学生获取奖学金申请记录排行")
    @GetMapping("/getApplySort")
    public CommonResult<List<ApplyResp>> getApplySort(@RequestParam("scholarshipId") Long scholarshipId){
        Long adminStuId = MyUtil.getCurrentAdminId();
        TbStudent student = iTbStudentService.getStudentByAdminId(adminStuId);
        TbClass tbClass = classService.getOne(new QueryWrapper<TbClass>().select("id, major_id, grade_id, description").eq("id", student.getClassId()));
        // 获取学生自己的集合
        OrderResultItem orderResultItem = orderResultItemService.getOne(new LambdaQueryWrapper<OrderResultItem>().eq(OrderResultItem::getClassId, tbClass.getId()));
        if (Objects.isNull(orderResultItem)){
            return CommonResult.failed("集合不存在，请联系管理员");
        }

        List<ApplyResp> orderSort = iTbApplyService.getOrderSort(orderResultItem.getOrderResultId(), scholarshipId);
        return CommonResult.success(orderSort);
    }

    @ApiOperation("学工办获取奖学金申请排行")
    @GetMapping("/manager/getApplySort")
    public CommonResult<List<ApplyResp>> managerApplySort(@RequestParam("resultId") Long resultId,
                                         @RequestParam("scholarshipId") Long scholarshipId){
        List<ApplyResp> orderSort = iTbApplyService.getOrderSort(resultId, scholarshipId);
        return CommonResult.success(orderSort);
    }


}
